package com.allen.app.common.utils;

import java.util.Objects;

/**
 * @Classname ThreadLoaclHelper
 * @Description 本地线程绑定工具类
 * @Date 2020/3/16 0016 11:38
 * @Created by Limiaojun
 */
public class ThreadLocalHelper {
    private static final String THREAD_LOCAL_INI ="ThreadLocalHelper.init";
    //线程本地环境
    private static final ThreadLocal<Object> THREAD_LOCAL = ThreadLocal.withInitial(() -> "ThreadLocalHelper.init");

    //绑定数据
    public static void bingData(Object obj) {
        THREAD_LOCAL.set(obj);
    }
    //获取数据
    public static Object getDataObj() {
        Object obj = THREAD_LOCAL.get();
        try {

            //如果为空或者初始值 返回null
            if (Objects.isNull(obj) || Objects.equals(THREAD_LOCAL_INI, obj)) {
                return null;
            }
            return obj;
        } finally {
            clearData();
        }
    }

    //获取数据
    public static <T> T getData(){
        return(T) getDataObj();
    }
    //清除数据
    public static void clearData() {
        THREAD_LOCAL.remove();
    }

//    public static void main(String[] args) {
//        final CountDownLatch begin = new CountDownLatch(1);
//
//        for (int i = 0; i < 20; i++) {
//            //优化本地线程池数据绑定脏数据
//            int finalI = i;
//            ThreadManager.getThreadPool().execute(() -> {
//                if(finalI % 2 == 0){
//                    bingData(finalI);
//                }
//                System.out.println(Thread.currentThread().getName() +":\t"+ getDataObj());
//            });
//        }
//        begin.countDown();
//        Try.tryCatch(()->Thread.sleep(1000L));
//        System.exit(0);
//    }
}
